package com.lin.java.tool.websocket.message;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @作者: 林江
 * @创建时间: 2024/4/17
 * @功能:
 */
@Slf4j
public class MessageHandler extends AbstractWebSocketHandler {
    // 存放用户所对应的session，也可以放入缓存中
    Map<String, WebSocketSession> container = new ConcurrentHashMap<>();

    /**
     * 连接websocket之前
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("连接websocket之前,sessionId={}", session.getId());
        container.put(session.getId(), session);
    }

    /**
     * 处理文本类消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(message);
    }

    /**
     * 处理二进制消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        System.out.println(message);
    }

    /**
     * 处理ping消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        System.out.println(message);
    }

    /**
     * 异常时的处理方式
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("webscoket传输异常，{}", exception);
        container.remove(session.getId());
    }

    /**
     * webscoket连接关闭时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("webscoket连接关闭之后");
        container.remove(session.getId());
    }

    /**
     * 推送数据
     *
     * @param msg
     * @throws IOException
     */
    public void send(String msg) throws IOException {
        for (WebSocketSession session : container.values()) {
            TextMessage message = new TextMessage(msg);
            session.sendMessage(message);
        }
    }
}
